#include "APP.h"
#include <iostream>   

APP::APP(void) {}

APP::APP(Controller* controller)
{
	this->controller = controller;
}

bool isExitEvent(SDL_Event &e) {
	if (e.type == SDL_QUIT)
	{
		return true;
	}
	return false;
}

int APP::start(void) {
	this->controller->getView()->createWindow();
	bool quit = !this->controller->loadView();
	this->controller->setFlagContinue(false);
	SDL_Event e;
	
	// Bucle principal del juego
	while (!quit)
	{
		while (SDL_PollEvent(&e) != 0)
		{
			if (isExitEvent(e)) {
				quit = true;
				break;
			} else {
				Controller* newController = this->controller->handleEvent(&e);
				if (newController != NULL) {
					delete this->controller;
					this->controller = newController;
				}				
			}
		}
		
		if (controller->getFlagContinue()) {
			this->controller->updateView();
			this->controller->updateModel();
			SDL_Delay(Constants::FRAMERATE / StageParser::getInstance()->getGameStageData().getSimulationVe());
		}
	}
	return FINISH_APP;
}

APP::~APP(void) {
	this->controller->getView()->close();
	delete this->controller;
}
